import axios from 'axios';

/**
 * 从 localStorage 获取用户 ID
 * @returns {string} - 用户 ID
 */
const getUserId = () => {
    const userInfo = localStorage.getItem('user_info');
    if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };

    try {
        const parsedUserInfo = JSON.parse(userInfo);
        return parsedUserInfo.id;
    } catch (error) {
        throw { msg: '用户信息解析失败' };
    }
};

/**
 * 添加用户资产
 * @param {Object} assetData - 资产数据
 * @param {string} assetData.userid - 用户ID
 * @param {string} assetData.products_id - 产品代码
 * @param {string} assetData.products_name - 产品名称
 * @param {string} assetData.type - 资产类型 (股票、债券、基金、外汇)
 * @param {number} assetData.quantity - 持仓数量
 * @param {string} assetData.buy_time - 购入时间 (格式：YYYY-MM-DD HH:mm:ss)
 * @returns {Promise<Object>} - API 响应
 */



export const $addUserAsset = async (assetData) => {
    try {
        console.log('/api/asset/add_asset');
        const userId = getUserId(); // 自动获取用户 ID
        const response = await axios.post('/api/asset/add_asset', { ...assetData, userid: userId });
        return response.data;
    } catch (error) {
        throw error.response?.data || { msg: 'Api添加资产失败' };
    }
};

/**
 * 获取用户资产列表
 * @returns {Promise<Object>} - API 响应
 */
export const $getUserAssets = async () => {
    try {
        const userId = getUserId(); // 自动获取用户 ID
        const response = await axios.get(`/api/asset/list?userid=${userId}`);
        console.log(response.data);
        return response.data;
    } catch (error) {
        throw error.response?.data || { msg: 'Api获取资产列表失败' };
    }
};

/**
 * 删除用户资产
 * @param {number} products_id - 资产ID
 * @returns {Promise<Object>} - API 响应
 */
export const $deleteUserAsset = async (products_id) => {
    try {
        const response = await axios.delete(`/api/asset/delete/${products_id}`);
        return response.data;
    } catch (error) {
        throw error.response?.data || { msg: '删除资产失败' };
    }
};